<template>
  <div class="user-management">
    <el-card class="user-list-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <!-- 添加用户按钮 -->
            <el-button type="primary" @click="showAddDialog = true">
              <el-icon>
                <Plus />
              </el-icon>
              添加用户
            </el-button>
          </div>
          <div class="header-right">
            <!-- 搜索输入框 -->
            <el-input v-model="searchKeyword" placeholder="搜索用户名、邮箱或手机" style="width: 250px; margin-right: 10px;"
              clearable @input="handleSearch" @clear="handleSearch">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <!-- 状态过滤下拉框 -->
            <el-select v-model="statusFilter" placeholder="所有状态" style="width: 120px; margin-right: 10px;"
              @change="loadUsers">
              <el-option label="所有状态" value="" />
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="2" />
            </el-select>
            <!-- 重置按钮 -->
            <el-button @click="resetFilters" type="default">
              <el-icon>
                <Refresh />
              </el-icon>
              重置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 用户列表表格 -->
      <div class="table-wrapper">
        <el-table 
          :data="filteredUsers" 
          v-loading="loading" 
          element-loading-text="加载中..."
          empty-text="暂无数据"
          class="centered-table">
          <!-- 用户信息列：头像和用户名 -->
          <el-table-column label="用户信息" min-width="180" show-overflow-tooltip align="center" class-name="user-info-column">
            <template #default="{ row }">
              <div class="user-info">
                <!-- 用户头像 -->
                <el-avatar 
                  :size="40" 
                  :src="row.avatar ? `${baseUrl}${row.avatar}` : ''"
                  :style="{ background: row.avatar ? 'transparent' : '#667eea' }"
                >
                  <span v-if="!row.avatar && row.username" style="color: white; font-size: 16px; font-weight: 600;">
                    {{ row.username.charAt(0).toUpperCase() }}
                  </span>
                  <el-icon v-else-if="!row.avatar && !row.username" style="color: white; font-size: 16px;">
                    <User />
                  </el-icon>
                </el-avatar>
                <div class="user-details">
                  <div class="user-name">
                    <!-- 编辑模式下显示输入框，否则显示用户名 -->
                    <el-input v-if="editingRowId === row.id" v-model="row.username" placeholder="请输入用户名" size="small" />
                    <el-tooltip v-else :content="row.username" placement="top">
                      <span class="username-text">{{ row.username }}</span>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <!-- 邮箱列 -->
          <el-table-column prop="email" label="邮箱" min-width="200" align="center" class-name="email-column">
            <template #default="{ row }">
              <!-- 编辑模式下显示输入框 -->
              <div v-if="editingRowId === row.id">
                <el-input v-model="row.email" size="small" />
              </div>
              <div v-else>{{ row.email }}</div>
            </template>
          </el-table-column>
          <!-- 手机号列 -->
          <el-table-column prop="phone" label="手机号" min-width="150" align="center" class-name="phone-column">
            <template #default="{ row }">
              <!-- 编辑模式下显示输入框 -->
              <div v-if="editingRowId === row.id">
                <el-input v-model="row.phone" size="small" />
              </div>
              <div v-else>{{ maskPhone(row.phone) }}</div>
            </template>
          </el-table-column>
          <!-- 角色列 -->
          <el-table-column prop="role" label="角色" min-width="120" align="center" class-name="role-column">
            <template #default="{ row }">
              <el-tag :type="getRoleType(row.role || '')">
                {{ row.roleName || getRoleName(row.role || '') }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 状态列 -->
          <el-table-column prop="status" label="状态" min-width="100" align="center" class-name="status-column">
            <template #default="{ row }">
              <!-- 编辑模式下显示切换按钮 -->
              <div v-if="editingRowId === row.id">
                <el-button :type="row.status === '0' ? 'success' : 'danger'" size="small" @click="toggleUserStatus(row)"
                  style="width: 100%">
                  <el-icon v-if="row.status === '0'">
                    <Check />
                  </el-icon>
                  <el-icon v-else>
                    <Close />
                  </el-icon>
                  {{ row.status === '0' ? '启用中' : '禁用中' }}
                </el-button>
              </div>
              <!-- 非编辑模式下显示状态标签 -->
              <el-tag v-else :type="getStatusType(row.status || '')">
                {{ getStatusName(row.status || '') }}
              </el-tag>
            </template>
          </el-table-column>
          <!-- 操作列 -->
          <el-table-column label="操作" min-width="200" fixed="right" align="center" class-name="operation-column">
            <template #default="{ row }">
              <div class="operation-buttons">
                <!-- 查看用户详情按钮 -->
                <el-button type="text" size="small" @click="viewUser(row)">
                  <el-icon>
                    <View />
                  </el-icon>
                </el-button>
                <!-- 角色分配按钮 -->
                <el-button type="text" size="small" @click="assignRolesHandler(row)">
                  <el-icon>
                    <User />
                  </el-icon>
                  角色
                </el-button>
                <!-- 编辑模式下的操作按钮 -->
                <div v-if="editingRowId === row.id">
                  <!-- 保存编辑按钮 -->
                  <el-button type="text" size="small" @click="saveEdit(row.id)" style="color: #67c23a;">
                    <el-icon>
                      <Check />
                    </el-icon>
                  </el-button>
                  <!-- 取消编辑按钮 -->
                  <el-button type="text" size="small" @click="cancelEdit" style="color: #f56c6c;">
                    <el-icon>
                      <Close />
                    </el-icon>
                  </el-button>
                </div>
                <!-- 非编辑模式下的操作按钮 -->
                <div v-else>
                  <!-- 开始编辑按钮 -->
                  <el-button type="text" size="small" @click="openEdit(row.id)">
                    <el-icon>
                      <Edit />
                    </el-icon>
                  </el-button>
                  <!-- 删除用户按钮 -->
                  <el-button type="text" size="small" @click="deleteUserHandler(row)" style="color: #f56c6c;">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="showAddDialog" title="添加用户" width="500px">
      <el-form :model="userForm" :rules="userRules" ref="userFormRef" label-width="100px">
        <!-- 用户名字段 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <!-- 邮箱字段 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <!-- 手机号字段 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <!-- 密码字段 -->
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="addUserHandler" :loading="addingUser">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="用户详情" width="600px">
      <div class="user-detail">
        <!-- 用户详情头部：头像和基本信息 -->
        <div class="detail-header">
          <el-avatar 
            :size="100" 
            :src="selectedUserDetail.avatar ? `${baseUrl}${selectedUserDetail.avatar}` : ''"
            :style="{ background: selectedUserDetail.avatar ? 'transparent' : '#667eea' }"
          >
            <span v-if="!selectedUserDetail.avatar && selectedUserDetail.username" style="color: white; font-size: 32px; font-weight: 600;">
              {{ selectedUserDetail.username.charAt(0).toUpperCase() }}
            </span>
            <el-icon v-else-if="!selectedUserDetail.avatar && !selectedUserDetail.username" style="color: white; font-size: 32px;">
              <User />
            </el-icon>
          </el-avatar>
          <div class="detail-info">
            <h3>{{ selectedUserDetail.username }}</h3>
            <div class="detail-meta">
              <!-- 邮箱信息 -->
              <span class="meta-item">
                <el-icon>
                  <Message />
                </el-icon>
                {{ selectedUserDetail.email }}
              </span>
              <!-- 手机号信息 -->
              <span class="meta-item">
                <el-icon>
                  <Phone />
                </el-icon>
                {{ selectedUserDetail.phone }}
              </span>
            </div>
          </div>
        </div>
        <el-divider />
        <!-- 用户详情内容 -->
        <div class="detail-content">
          <el-row :gutter="20">
            <!-- 左侧信息 -->
            <el-col :span="12">
              <!-- 用户ID -->
         
              <!-- 角色信息 -->
              <div class="detail-item">
                <label>角色:</label>
                <el-tag :type="getRoleType(selectedUserDetail.role || '')">
                  {{ selectedUserDetail.roleName || getRoleName(selectedUserDetail.role || '') }}
                </el-tag>
              </div>
              <!-- 状态信息 -->
              <div class="detail-item">
                <label>状态:</label>
                <el-tag :type="getStatusType(selectedUserDetail.status || '')">
                  {{ getStatusName(selectedUserDetail.status || '') }}
                </el-tag>
              </div>
            </el-col>
            <!-- 右侧信息 -->
            <el-col :span="12">
              <!-- 注册时间 -->
              <div class="detail-item">
                <label>注册时间:</label>
                <span>{{ new Date(selectedUserDetail.createdAt).toLocaleString() }}</span>
              </div>
              <!-- 最后登录时间 -->
              <div class="detail-item">
                <label>最后登录:</label>
                <span>{{ new Date(selectedUserDetail.createdAt).toLocaleString() || '从未登录' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <!-- 角色分配弹窗 -->
    <el-dialog v-model="showAssignRoleDialog" title="分配角色" width="700px" class="assign-role-dialog" :close-on-click-modal="false">
      <div class="assign-role-header">
        <el-avatar 
          :size="60" 
          :src="selectedUserDetail.avatar ? `${baseUrl}${selectedUserDetail.avatar}` : ''"
          :style="{ background: selectedUserDetail.avatar ? 'transparent' : '#667eea' }"
        >
          <span v-if="!selectedUserDetail.avatar && selectedUserDetail.username" style="color: white; font-size: 24px; font-weight: 600;">
            {{ selectedUserDetail.username.charAt(0).toUpperCase() }}
          </span>
          <el-icon v-else-if="!selectedUserDetail.avatar && !selectedUserDetail.username" style="color: white; font-size: 24px;">
            <User />
          </el-icon>
        </el-avatar>
        <div class="user-info">
          <div class="user-name">{{ selectedUserDetail.username || '未知用户' }}</div>
          <div class="user-email">{{ selectedUserDetail.email || '无邮箱信息' }}</div>
        </div>
      </div>
      <div class="current-role-box">
        <div>当前角色</div>
        <div class="role-tags">
          <el-tag
            v-for="role in selectedUserDetail.roles"
            :key="role.id"
            type="info"
            effect="plain"
            style="margin-right: 6px;"
          >{{ role.roleName }}</el-tag>
          <el-tag v-if="selectedUserDetail.roles && selectedUserDetail.roles.length > 2" type="info" effect="plain">
            +{{ selectedUserDetail.roles.length - 2 }}
          </el-tag>
        </div>
      </div>
      <div class="select-role-box">
        <div class="select-role-title">
          选择角色
          <span class="selected-count">已选择 {{ selectedRoles.length }} 个角色</span>
        </div>
        <div class="role-list-container">
          <el-checkbox-group v-model="selectedRoles">
            <div
              v-for="role in allRoles"
              :key="role.id"
              class="role-card"
            >
              <el-checkbox :label="role.id">
                <div>
                  <div class="role-name">{{ role.roleName }}</div>
                  <div class="role-desc">{{ role.roleDescription }}</div>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAssignRoles">取消</el-button>
          <el-button type="primary" @click="saveAssignRoles" :loading="assigningRole">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import {
  getUserList,
  addUser,
  updateUser,
  deleteUser,
  enableUser,
  disableUser,
  getUserDetail,
  getUserRoles,
  getAllRoles,
  assignUserRoles
} from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, View, Edit, Delete,
  Message, Phone, Check, Close, Refresh, User
} from '@element-plus/icons-vue'

// ==================== 响应式数据定义 ====================

// 加载状态控制
const loading = ref(false)
const addingUser = ref(false)
const assigningRole = ref(false)
// 对话框显示状态控制
const showAddDialog = ref(false)           // 添加用户对话框
const showDetailDialog = ref(false)        // 用户详情对话框
const showAssignRoleDialog = ref(false)    // 角色分配对话框
// 用户详情数据
const selectedUserDetail = ref({
  id: '',
  username: '',
  email: '',
  phone: '',
  role: '',
  roleName: '',
  status: '',
  avatar: '',
  createdAt: '',
  lastLoginAt: '',
  roles: []
})
//页码
let formSize=ref({
  page:1,
  size:10
})
const baseUrl = ref('http://api-rag.monkeymeerkat.cn/api/users/avatar-file/')
// 角色分配相关数据
const allRoles = ref([])           // 所有可选角色
const selectedRoles = ref([])      // 已选角色id
// 分页相关数据
const pageSize = ref(10)                   // 每页显示条数
// 搜索和过滤相关数据
const searchKeyword = ref('')              // 搜索关键词
const statusFilter = ref('')               // 状态过滤条件

// 行内编辑相关数据
const editingRowId = ref(null)             // 当前正在编辑的行ID
// 备份原始行数据，用于取消编辑时恢复
let backupRow = null

// 用户数据列表
const users = ref([])
const total = ref(0)
const currentPage = ref(1)

// 表单引用
const userFormRef = ref(null)

// 搜索防抖定时器
let searchTimer = null

// 添加用户表单数据
const userForm = reactive({
  username: '',
  email: '',
  password: '',
  phone: '',
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// ==================== 计算属性 ====================

/**
 * 过滤后的用户列表
 * 根据搜索关键词和状态过滤条件过滤用户数据
 */
const filteredUsers = computed(() => {
  let filtered = users.value

  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(user =>
      (user.username && user.username.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
      (user.email && user.email.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
      (user.phone && user.phone.includes(searchKeyword.value))
    )
  }

  // 根据状态过滤
  if (statusFilter.value) {
    filtered = filtered.filter(user => user.status === statusFilter.value)
  }

  return filtered
})

// ==================== 工具函数 ====================

/**
 * 获取角色名称
 * @param {string} role - 角色标识
 * @returns {string} 角色显示名称
 */
const getRoleName = (role) => {
  if (!role) return '未分配'
  const roleMap = {
    'admin': '管理员',
    'editor': '编辑者',
    'viewer': '查看者',
    'user': '普通用户'
  }
  return roleMap[role] || role
}

/**
 * 获取角色类型（用于标签颜色）
 * @param {string} role - 角色标识
 * @returns {string} 角色标签类型
 */
const getRoleType = (role) => {
  const typeMap = {
    'admin': 'danger',
    'editor': 'warning',
    'viewer': 'info',
    'user': 'primary'
  }
  return typeMap[role] || 'info'
}

/**
 * 获取状态名称
 * @param {string} status - 状态标识
 * @returns {string} 状态显示名称
 */
const getStatusName = (status) => {
  if (!status) return '未知'
  const statusMap = {
    '0': '启用',
    '2': '禁用',
  }
  return statusMap[status] || status
}

/**
 * 获取状态类型（用于标签颜色）
 * @param {string} status - 状态标识
 * @returns {string} 状态标签类型
 */
const getStatusType = (status) => {
  const typeMap = {
    '0': 'success',
    '2': 'danger',
    'pending': 'warning'
  }
  return typeMap[status] || 'info'
}

/**
 * 手机号脱敏处理
 * @param {string} phone - 原始手机号
 * @returns {string} 脱敏后的手机号
 */
const maskPhone = (phone) => {
  if (!phone || typeof phone !== 'string') return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// ==================== 数据加载函数 ====================

/**
 * 加载用户列表数据
 * 从后端API获取用户数据并更新本地状态
 */
const loadUsers = async () => {
  loading.value = true
  try {
    const res = await getUserList(formSize.value)
   console.log(res);
   
    
    if (res.code === 200 && res.data) {
      // 数据格式转换
      const userData = res.data.users || res.data
      if (Array.isArray(userData)) {
        users.value = userData.map(u => {
          // 获取角色信息
          let roleIdentifier = 'user' // 默认角色标识
          let roleDisplayName = '未分配' // 默认显示名称
          
          if (u.roles && u.roles[0]) {
            const role = u.roles[0]
            roleDisplayName = role.roleName || '未分配'
            // 根据角色名称映射到角色标识
            if (role.roleName === '超级管理员') {
              roleIdentifier = 'admin'
            } else if (role.roleName === '编辑者') {
              roleIdentifier = 'editor'
            } else if (role.roleName === '查看者') {
              roleIdentifier = 'viewer'
            } else if (role.roleName === '普通用户') {
              roleIdentifier = 'user'
            } else {
              roleIdentifier = role.roleName || 'user'
            }
          } else if (u.role) {
            roleIdentifier = u.role
            roleDisplayName = getRoleName(u.role)
          }
          
          return {
            id: u.id,
            username: u.userName || u.username,
            email: u.email,
            phone: u.phoneNumber || u.phone,
            role: roleIdentifier,
            roleName: roleDisplayName,
            status: u.accountStatus === 0 ? '0' : (u.accountStatus === 2 ? '2' : '0'),
            avatar: u.avatar,
            createdAt: u.createdAt,
            lastLoginAt: u.lastLoginTime || u.lastLoginAt
          }
        })
        total.value = res.data.total || users.value.length
      } else {
        users.value = []
        total.value = 0
      }
    } else {
      users.value = []
      total.value = 0
      if (res.message) {
        ElMessage.warning(res.message)
      }
    }
  } catch (e) {
    console.error('加载用户列表失败:', e)
    users.value = []
    total.value = 0
    ElMessage.error('加载用户列表失败，请检查网络连接')
  }
  loading.value = false
}

// ==================== 事件处理函数 ====================

/**
 * 处理搜索输入（防抖）
 */
const handleSearch = () => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    currentPage.value = 1
    loadUsers()
  }, 500)
}

/**
 * 重置搜索和过滤条件
 */
const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  loadUsers()
}





/**
 * 查看用户详情
 * @param {Object} user - 用户对象
 */
const viewUser = async (user) => {
  try {
    const res = await getUserDetail(user.id)
    if (res.code === 200 && res.data) {
      selectedUserDetail.value = {
        ...res.data,
        avatar: res.data.avatar || '',
        username: res.data.username || res.data.userName || '',
        email: res.data.email || ''
      }
      
      console.log('查看用户详情 - 用户信息:', {
        id: selectedUserDetail.value.id,
        username: selectedUserDetail.value.username,
        avatar: selectedUserDetail.value.avatar,
        baseUrl: baseUrl.value,
        fullAvatarUrl: selectedUserDetail.value.avatar ? `${baseUrl.value}${selectedUserDetail.value.avatar}` : '无头像'
      })
      
      showDetailDialog.value = true
    } else {
      ElMessage.error('获取用户详情失败')
    }
  } catch (e) {
    console.error('获取用户详情失败:', e)
    ElMessage.error('获取用户详情失败')
  }
}

/**
 * 打开编辑模式
 * @param {number} id - 要编辑的用户ID
 */
const openEdit = (id) => {
  editingRowId.value = id
  // 查找对应的行数据并备份
  const row = users.value.find(item => item.id === id)
  backupRow = { ...row }
}

/**
 * 切换用户状态
 * @param {Object} user - 用户对象
 */
const toggleUserStatus = (user) => {
  // 切换状态：0 -> 2, 2 -> 0
  user.status = user.status === '0' ? '2' : '0'
}

/**
 * 角色分配处理
 * @param {Object} user - 用户对象
 */
const assignRolesHandler = async (user) => {
  // 重置选择状态
  selectedRoles.value = []
  
  // 确保用户信息完整，包括头像字段
  selectedUserDetail.value = { 
    ...user,
    avatar: user.avatar || '',
    username: user.username || user.userName || '',
    email: user.email || ''
  }
  
  console.log('分配角色 - 用户信息:', {
    id: selectedUserDetail.value.id,
    username: selectedUserDetail.value.username,
    avatar: selectedUserDetail.value.avatar,
    baseUrl: baseUrl.value
  })
  
  showAssignRoleDialog.value = true
  
  try {
    // 获取所有角色
    const res = await getAllRoles()
    if (res.code === 200 && res.data) {
      allRoles.value = res.data.roles || []
    }
    
    // 获取用户已分配角色
    const res2 = await getUserRoles(user.id)
    if (res2.code === 200 && res2.data) {
      // 兼容 roles 字段或数组
      if (Array.isArray(res2.data.roles)) {
        selectedRoles.value = res2.data.roles.map(r => r.id)
        selectedUserDetail.value.roles = res2.data.roles
      } else if (Array.isArray(res2.data)) {
        selectedRoles.value = res2.data.map(r => r.id)
        selectedUserDetail.value.roles = res2.data
      } else {
        selectedRoles.value = []
        selectedUserDetail.value.roles = []
      }
    } else {
      selectedRoles.value = []
      selectedUserDetail.value.roles = []
    }
    
    // 等待DOM更新完成后，确保滚动容器正常工作
    await nextTick()
    console.log('角色数据加载完成，角色数量:', allRoles.value.length)
    
    // 强制重新计算滚动容器的尺寸
    const roleListContainer = document.querySelector('.role-list-container')
    if (roleListContainer) {
      console.log('滚动容器当前状态:', {
        scrollHeight: roleListContainer.scrollHeight,
        clientHeight: roleListContainer.clientHeight,
        scrollTop: roleListContainer.scrollTop
      })
      
      // 确保滚动条可见
      if (roleListContainer.scrollHeight > roleListContainer.clientHeight) {
        console.log('内容超出容器，滚动条应该可见')
      } else {
        console.log('内容未超出容器，滚动条可能不可见')
      }
    }
  } catch (e) {
    console.error('加载角色数据失败:', e)
    ElMessage.error('加载角色数据失败')
  }
}

/**
 * 保存角色分配
 */
const saveAssignRoles = async () => {
  assigningRole.value = true
  try {
    await assignUserRoles(selectedUserDetail.value.id, selectedRoles.value)
    ElMessage.success('分配角色成功')
    showAssignRoleDialog.value = false
    loadUsers() // 刷新用户列表
  } catch (e) {
    console.error('分配角色失败:', e)
    ElMessage.error('分配失败')
  } finally {
    assigningRole.value = false
  }
}

/**
 * 取消角色分配
 */
const cancelAssignRoles = () => {
  selectedRoles.value = []
  showAssignRoleDialog.value = false
}

/**
 * 保存编辑内容
 * @param {number} id - 要保存的用户ID
 */
const saveEdit = async (id) => {
  try {
    // 查找要编辑的用户
    const editUser = users.value.find(item => item.id === id)
    const originalUser = backupRow

    // 调用API更新用户基本信息
    await updateUser(id, {
      userName: editUser.username,
      email: editUser.email,
      phoneNumber: editUser.phone
    })

    // 如果状态发生变化，调用相应的启用/禁用函数
    if (editUser.status !== originalUser.status) {
      if (editUser.status === '0') {
        await enableUser(id)
      } else if (editUser.status === '2') {
        await disableUser(id)
      }
    }

    ElMessage.success('更新用户成功')
    editingRowId.value = null
    loadUsers()
  } catch (e) {
    console.error('更新用户失败:', e)
    ElMessage.error('更新失败')
  }
}

/**
 * 取消编辑
 * 恢复原始数据，退出编辑模式
 */
const cancelEdit = () => {
  if (editingRowId.value !== null && backupRow) {
    // 找到对应的行索引
    const idx = users.value.findIndex(item => item.id === editingRowId.value)
    if (idx !== -1) {
      // 恢复原始数据
      Object.assign(users.value[idx], backupRow)
    }
  }
  // 重置编辑状态
  editingRowId.value = null
  backupRow = null
}

/**
 * 删除用户
 * @param {Object} user - 要删除的用户对象
 */
const deleteUserHandler = async (user) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 ${user.username} 吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteUser(user.id)
    ElMessage.success('删除成功')
    loadUsers()
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 启用用户
 * @param {Object} user - 要启用的用户对象
 */
const handleEnableUser = async (user) => {
  try {
    await enableUser(user.id)
    ElMessage.success('启用成功')
    loadUsers()
  } catch (e) {
    console.error('启用用户失败:', e)
    ElMessage.error('启用失败')
  }
}

/**
 * 禁用用户
 * @param {Object} user - 要禁用的用户对象
 */
const handleDisableUser = async (user) => {
  try {
    await disableUser(user.id)
    ElMessage.success('禁用成功')
    loadUsers()
  } catch (e) {
    console.error('禁用用户失败:', e)
    ElMessage.error('禁用失败')
  }
}

/**
 * 添加用户
 * 验证表单数据，调用API添加用户，成功后刷新列表
 */
const addUserHandler = async () => {
  console.log('开始添加用户...')
  console.log('表单数据:', userForm)

  if (!userFormRef.value) {
    console.error('表单引用不存在')
    return
  }

  addingUser.value = true

  try {
    console.log('开始表单验证...')
    await userFormRef.value.validate()
    console.log('表单验证通过')

    const userData = {
      userName: userForm.username,
      password: userForm.password,
      email: userForm.email,
      phoneNumber: userForm.phone
    }
    console.log('准备调用API，数据:', userData)

    const result = await addUser(userData)
    console.log('API调用结果:', result)

    ElMessage.success('添加用户成功')
    showAddDialog.value = false

    // 重置表单
    Object.assign(userForm, {
      username: '',
      email: '',
      password: '',
      phone: ''
    })

    // 刷新用户列表
    await loadUsers()
    console.log('用户列表已刷新')

  } catch (e) {
    console.error('添加用户失败:', e)
    if (e !== false) { // 表单验证失败时 e 为 false
      ElMessage.error(`添加用户失败: ${e.message || e}`)
    }
  } finally {
    addingUser.value = false
  }
}

// ==================== 分页处理函数 ====================

/**
 * 处理每页显示条数变化
 * @param {number} val - 新的每页条数
 */
const handleSizeChange = (val) => {

  formSize.value.size=val
  console.log(formSize.value);
  
  loadUsers()
}

/**
 * 处理当前页码变化
 * @param {number} val - 新的页码
 */
const handleCurrentChange = (val) => {
  formSize.page=val
  console.log(formSize.value);
  
  loadUsers()
}

// ==================== 生命周期钩子 ====================

/**
 * 组件挂载时执行
 * 初始化获取用户列表数据
 */
onMounted(() => {
  loadUsers()
  // 测试API连接
  console.log('组件已挂载，测试API连接...')
})

/**
 * 监听角色分配对话框状态变化
 */
watch(showAssignRoleDialog, async (newVal) => {
  if (newVal) {
    // 对话框打开后，等待DOM更新完成，然后确保滚动容器正常工作
    await nextTick()
    console.log('角色分配对话框已打开，初始化滚动容器...')
    
    // 强制重新计算滚动容器的尺寸
    const roleListContainer = document.querySelector('.role-list-container')
    if (roleListContainer) {
      console.log('找到滚动容器，当前高度:', roleListContainer.scrollHeight)
      // 触发重新布局
      roleListContainer.style.display = 'none'
      roleListContainer.offsetHeight // 触发重排
      roleListContainer.style.display = 'block'
      console.log('滚动容器重新布局完成')
    }
  }
})

/**
 * 组件卸载时执行
 * 清理定时器
 */
onUnmounted(() => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
})
</script>

<style scoped>
/* 用户管理主容器 */
.user-management {
  padding: 30px;
  min-height: calc(100vh - 120px);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  box-sizing: border-box;
}

/* 用户列表卡片样式 */
.user-list-card {
  margin-bottom: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  width: 100%;
  max-width: 1400px;
  margin: 0 auto 20px auto;
  align-self: center;
}

.user-list-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-bottom: 1px solid rgba(226, 232, 240, 0.8);
  position: relative;
  width: 100%;
  box-sizing: border-box;
}

.card-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}

/* 头部左侧按钮组 */
.header-left {
  display: flex;
  gap: 15px;
}

.header-left .el-button {
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.header-left .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

/* 头部右侧搜索和过滤区域 */
.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-right .el-input {
  border-radius: 12px;
  transition: all 0.3s ease;
}

.header-right .el-input:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-right .el-select {
  border-radius: 12px;
}

.header-right .el-button {
  border-radius: 12px;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

.header-right .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 用户信息显示区域 */
.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 8px;
  border-radius: 12px;
  transition: background-color 0.3s ease;
}

.user-info:hover {
  background: rgba(102, 126, 234, 0.05);
}

/* 用户头像样式 */
.user-info .el-avatar {
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.user-info:hover .el-avatar {
  transform: scale(1.1);
}

/* 用户详情信息 */
.user-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

/* 用户名样式 */
.user-name {
  font-weight: 600;
  color: #2d3748;
  font-size: 14px;
}

/* 用户名文本省略号样式 */
.username-text {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  color: #4a5568;
}

/* 表格包装器居中 */
.table-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

/* 表格容器样式 */
.user-list-card .el-card__body {
  padding: 0;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 表格样式 */
:deep(.el-table) {
  background: transparent;
  border-radius: 16px;
  overflow: hidden;
  width: 100% !important;
  margin: 0 auto !important;
  table-layout: fixed;
}

/* 表格头部样式 */
:deep(.el-table__header) {
  background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
  width: 100% !important;
}

:deep(.el-table__header th) {
  background: transparent;
  color: #4a5568;
  font-weight: 600;
  padding: 20px 16px;
  border-bottom: 2px solid #e2e8f0;
  text-align: center !important;
}

/* 表格主体样式 */
:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__body tr) {
  transition: all 0.3s ease;
  width: 100% !important;
}

:deep(.el-table__body tr:hover) {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  transform: scale(1.01);
}

:deep(.el-table__body td) {
  padding: 20px 16px;
  border-bottom: 1px solid rgba(226, 232, 240, 0.6);
  text-align: center !important;
}

/* 表格单元格居中 */
:deep(.el-table .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

/* 表格头部单元格居中 */
:deep(.el-table__header .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

/* 特定列的居中样式 */
:deep(.user-info-column .cell) {
  justify-content: center !important;
  align-items: center !important;
  text-align: center !important;
}

:deep(.email-column .cell) {
  justify-content: center !important;
  align-items: center !important;
  text-align: center !important;
}

:deep(.phone-column .cell) {
  justify-content: center !important;
  align-items: center !important;
  text-align: center !important;
}

:deep(.role-column .cell) {
  justify-content: center !important;
  align-items: center !important;
  text-align: center !important;
}

:deep(.status-column .cell) {
  justify-content: center !important;
  align-items: center !important;
  text-align: center !important;
}

:deep(.operation-column .cell) {
  justify-content: center !important;
  align-items: center !important;
  text-align: center !important;
}

/* 确保表格在所有设备上居中 */
@media (min-width: 1400px) {
  .user-list-card {
    max-width: 1400px;
    margin: 0 auto 20px auto;
  }
}

@media (max-width: 1399px) and (min-width: 769px) {
  .user-list-card {
    max-width: 95%;
    margin: 0 auto 20px auto;
  }
}

/* 标签样式升级 */
:deep(.el-tag) {
  border-radius: 8px;
  font-weight: 500;
  padding: 6px 12px;
  transition: all 0.3s ease;
}

:deep(.el-tag:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

/* 操作按钮组 */
.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.operation-buttons .el-button {
  border-radius: 8px;
  padding: 8px 12px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.operation-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 分页容器 */
.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 16px;
  margin: 30px auto;
  width: 100%;
  max-width: 1400px;
  align-self: center;
}

:deep(.el-pagination) {
  --el-pagination-button-bg-color: transparent;
  --el-pagination-button-color: #4a5568;
  --el-pagination-hover-color: #667eea;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.el-pagination .el-pager li:hover) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  transform: translateY(-1px);
}

:deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 对话框样式升级 */
:deep(.el-dialog) {
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__body) {
  padding: 30px;
}

:deep(.el-dialog__footer) {
  padding: 20px 30px;
  background: #f8fafc;
  border-top: 1px solid #e2e8f0;
}

/* 表单样式升级 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #4a5568;
}

:deep(.el-input__wrapper) {
  border-radius: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

/* 用户详情样式 */
.user-detail {
  padding: 30px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 16px;
}

/* 详情头部样式 */
.detail-header {
  display: flex;
  align-items: center;
  gap: 25px;
  margin-bottom: 30px;
  padding: 25px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* 详情信息标题 */
.detail-info h3 {
  margin: 0 0 15px 0;
  color: #2d3748;
  font-size: 24px;
  font-weight: 700;
}

/* 详情元信息 */
.detail-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 元信息项 */
.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #718096;
  font-size: 14px;
  padding: 8px 12px;
  background: rgba(102, 126, 234, 0.05);
  border-radius: 8px;
}

/* 详情内容区域 */
.detail-content {
  margin-top: 30px;
  background: white;
  border-radius: 16px;
  padding: 25px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

/* 详情项样式 */
.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.detail-item:hover {
  transform: translateX(5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 详情项标签 */
.detail-item label {
  width: 120px;
  font-weight: 600;
  color: #4a5568;
}

/* 详情项内容 */
.detail-item span {
  color: #2d3748;
  font-weight: 500;
}

/* 对话框底部按钮区域 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.dialog-footer .el-button {
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.dialog-footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 角色分配弹窗样式 */
.assign-role-dialog {
  /* 确保对话框不会影响主页面滚动 */
}

/* 当对话框打开时，防止主页面滚动 */
.assign-role-dialog:deep(.el-overlay) {
  overflow: hidden;
}

.assign-role-dialog:deep(.el-overlay-dialog) {
  overflow: hidden;
}

/* 确保对话框内容完全包含在对话框内 */
.assign-role-dialog:deep(.el-dialog__wrapper) {
  overflow: hidden;
}

.assign-role-dialog :deep(.el-dialog) {
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  /* 确保对话框本身不会超出视窗 */
  overflow: hidden;
}

.assign-role-dialog :deep(.el-dialog__body) {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
  /* 确保内容可以正常滚动 */
  overflow: hidden;
  min-height: 0;
  position: relative;
}

.assign-role-dialog .assign-role-header {
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px 20px 0 0;
  padding: 30px;
  color: white;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
}

.assign-role-dialog .assign-role-header::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

.assign-role-dialog .user-info {
  margin-left: 20px;
  position: relative;
  z-index: 1;
}

.assign-role-dialog .user-name {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 5px;
}

.assign-role-dialog .user-email {
  font-size: 16px;
  opacity: 0.9;
}

.current-role-box {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 0 0 16px 16px;
  padding: 20px 30px;
  margin-bottom: 25px;
  border-top: 3px solid #667eea;
  flex-shrink: 0;
}

.role-tags {
  margin-top: 10px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.select-role-box {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 16px;
  padding: 25px 30px;
  margin-bottom: 20px;
  border: 2px solid rgba(102, 126, 234, 0.1);
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  /* 确保这个容器不会超出父容器 */
  overflow: hidden;
  position: relative;
}

.role-list-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
  /* 设置固定高度确保滚动条始终显示 */
  height: 300px;
  min-height: 300px;
  /* 确保滚动条只在内部显示 */
  position: relative;
  /* 强制启用滚动 */
  overflow-x: hidden;
  overflow-y: scroll;
}

/* 自定义滚动条样式 */
.role-list-container::-webkit-scrollbar {
  width: 8px;
}

.role-list-container::-webkit-scrollbar-track {
  background: rgba(102, 126, 234, 0.1);
  border-radius: 4px;
}

.role-list-container::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  min-height: 40px;
}

.role-list-container::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
}

/* 确保滚动容器有足够的内容来触发滚动 */
.role-list-container .el-checkbox-group {
  width: 100%;
  min-height: 100%;
}

/* 对话框底部按钮样式 */
.assign-role-dialog :deep(.el-dialog__footer) {
  flex-shrink: 0;
  padding: 20px 30px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-top: 1px solid rgba(226, 232, 240, 0.8);
  border-radius: 0 0 20px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  width: 100%;
}

.assign-role-dialog :deep(.el-dialog__footer .el-button) {
  border-radius: 12px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.assign-role-dialog :deep(.el-dialog__footer .el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.select-role-title {
  font-weight: 600;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #2d3748;
  font-size: 18px;
  flex-shrink: 0;
}

.selected-count {
  color: #667eea;
  font-size: 16px;
  font-weight: 600;
  background: rgba(102, 126, 234, 0.1);
  padding: 6px 12px;
  border-radius: 8px;
}

.role-card {
  background: white;
  border-radius: 12px;
  margin-bottom: 15px;
  padding: 20px;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  flex-shrink: 0;
  /* 确保卡片不会超出容器 */
  max-width: 100%;
  box-sizing: border-box;
  /* 防止卡片被压缩 */
  min-height: 80px;
}

.role-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.role-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 12px 30px rgba(102, 126, 234, 0.15);
  border-color: rgba(102, 126, 234, 0.2);
}

.role-card:hover::before {
  transform: scaleX(1);
}

.role-card.selected {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-color: #667eea;
}

.role-card.selected::before {
  transform: scaleX(1);
}

.role-card .role-name {
  font-weight: 600;
  color: #2d3748;
  font-size: 16px;
  margin-bottom: 8px;
}

.role-card .role-desc {
  color: #718096;
  font-size: 14px;
  line-height: 1.5;
}

/* 加载状态样式 */
:deep(.el-loading-mask) {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(5px);
}

:deep(.el-loading-spinner) {
  color: #667eea;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-right {
    flex-wrap: wrap;
  }
  
  .operation-buttons {
    flex-wrap: wrap;
    gap: 8px;
  }
}

/* 表格列自适应样式 */
:deep(.el-table__cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center !important;
}

/* 确保表格充分利用容器宽度 */
:deep(.el-table__fixed) {
  width: 100% !important;
}

:deep(.el-table__fixed-right) {
  width: auto !important;
}

/* 表格滚动条样式 */
:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

/* 表格列宽度优化 */
:deep(.el-table-column--selection) {
  width: 50px;
}

/* 响应式表格居中 */
@media (max-width: 1400px) {
  .user-list-card {
    max-width: 95%;
    margin: 0 auto 20px auto;
  }
  
  .pagination-container {
    max-width: 95%;
    margin: 30px auto;
  }
}

@media (max-width: 768px) {
  .user-list-card {
    max-width: 100%;
    margin: 0 0 20px 0;
  }
  
  .pagination-container {
    max-width: 100%;
    margin: 20px 0;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-right {
    flex-wrap: wrap;
  }
  
  .operation-buttons {
    flex-wrap: wrap;
    gap: 8px;
  }
}

/* 确保表格完全居中的最终样式 */
.user-management {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 20px;
  box-sizing: border-box;
}

/* 用户列表卡片完全居中 */
.user-list-card {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto 20px auto;
  align-self: center;
}

/* 表格包装器完全居中 */
.table-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
}

/* 专门的居中表格样式 */
.centered-table {
  width: 100% !important;
  max-width: 100% !important;
  margin: 0 auto !important;
  display: block !important;
}

/* 表格居中样式 */
:deep(.el-table) {
  width: 100% !important;
  max-width: 100% !important;
  margin: 0 auto !important;
  table-layout: fixed !important;
  display: block !important;
}

/* 表格内部包装器居中 */
:deep(.el-table__inner-wrapper) {
  width: 100% !important;
  margin: 0 auto !important;
}

:deep(.el-table__header-wrapper) {
  width: 100% !important;
  margin: 0 auto !important;
  justify-self: center !important;
}

:deep(.el-table__body-wrapper) {
  width: 100% !important;
  margin: 0 auto !important;
  justify-self: center !important;
}

/* 表格头部居中 */
:deep(.el-table__header) {
  text-align: center !important;
  width: 100% !important;
  justify-self: center !important;
}

:deep(.el-table__header th) {
  text-align: center !important;
  vertical-align: middle !important;
  width: auto !important;
}

:deep(.el-table__header .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

/* 表格主体居中 */
:deep(.el-table__body td) {
  text-align: center !important;
  vertical-align: middle !important;
  width: auto !important;
}

:deep(.el-table__body .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

/* 特定列居中样式 */
:deep(.user-info-column .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

:deep(.email-column .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

:deep(.phone-column .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

:deep(.role-column .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

:deep(.status-column .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

:deep(.operation-column .cell) {
  text-align: center !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}

/* 强制所有表格内容居中 */
:deep(.el-table .el-table__column) {
  text-align: center !important;
}

:deep(.el-table .el-table__column-header) {
  text-align: center !important;
}

:deep(.el-table .el-table__column-content) {
  text-align: center !important;
}

/* 确保表格在容器中居中 */
.user-list-card .el-card__body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 0;
}

.user-list-card .el-card__body > * {
  width: 100%;
  max-width: 100%;
  margin: 0 auto;
}

/* 分页容器居中 */
.pagination-container {
  margin: 30px auto;
  width: 100%;
  max-width: 1400px;
  display: flex;
  justify-content: center;
}

/* 强制表格居中 - 使用更直接的方法 */
:deep(.el-table__fixed-header-wrapper) {
  width: 100% !important;
  margin: 0 auto !important;
  justify-self: center !important;
}

:deep(.el-table__fixed-body-wrapper) {
  width: 100% !important;
  margin: 0 auto !important;
  justify-self: center !important;
}

/* 确保表格行居中 */
:deep(.el-table__body tr) {
  text-align: center !important;
}

/* 覆盖任何可能的Element Plus默认样式 */
:deep(.el-table) {
  margin-left: auto !important;
  margin-right: auto !important;
}

:deep(.el-table__inner-wrapper) {
  margin-left: auto !important;
  margin-right: auto !important;
}


</style>